﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using MediaPortal.Configuration;
using MediaPortal.GUI.Library;

namespace MyNetflix2
{
    public partial class MyNetFlixConfig : Form
    {
        protected MyNetFlixData data = new MyNetFlixData();
        Queue queue = null;

        /// <summary>
        /// Constructor
        /// </summary>
        public MyNetFlixConfig()
        {
            InitializeComponent();

            //--------------------------------------------------------------------------------
            // Get the settings from the database and load them into the form
            //--------------------------------------------------------------------------------
            data.GetSettings();

            //--------------------------------------------------------------------------------
            // Set the # of results returned. Default to 100 if the first time opening form.
            //--------------------------------------------------------------------------------
            txtResults.Text = data.Results;
            
            if (data.Results == null || data.Results == "")
                txtResults.Text = "100";

            //--------------------------------------------------------------------------------
            // Set the Show Details and Instant Only flags
            //--------------------------------------------------------------------------------
            if (data.Details != "")
                chkDetails.Checked = bool.Parse(data.Details);
            if (data.InstantOnly != "")
                chInstantOnly.Checked = bool.Parse(data.InstantOnly);

            //--------------------------------------------------------------------------------
            // Load the instant users into the drop down
            //--------------------------------------------------------------------------------
            LoadInstantUsers();
            LoadQueueUsers();

            //--------------------------------------------------------------------------------
            // Load the screen information
            //--------------------------------------------------------------------------------
            foreach (Screen screen in Screen.AllScreens)
            {
                cbScreen.Items.Add((screen.Primary ? "Primary - " : "Secondary - ") + screen.DeviceName.Replace("\\", "").Replace(".", "") + " " + screen.WorkingArea.Width + " x " + screen.WorkingArea.Height);
            }
            cbScreen.SelectedIndex = data.DefaultScreen;
        }

        /// <summary>
        /// Loads the saved instant users into the drop down box
        /// </summary>
        private void LoadInstantUsers()
        {
            lbInstantUsers.Items.Clear();

            //--------------------------------------------------------------------------------
            // Get all the Instant Users
            //--------------------------------------------------------------------------------
            List<string> alUsers = data.GetInstantUsers();

            foreach (string user in alUsers)
            {
                lbInstantUsers.Items.Add(user);
            }
        }

        /// <summary>
        /// Loads the saved instant users into the drop down box
        /// </summary>
        private void LoadQueueUsers()
        {
            cbUsers.Items.Clear();
 
            //--------------------------------------------------------------------------------
            // Get all the Queue Users
            //--------------------------------------------------------------------------------
            List<string> alUsers = data.GetQueueUsers();

            foreach (string user in alUsers)
            {
                cbUsers.Items.Add(user);
            }
            if (alUsers.Count > 0)
                cbUsers.SelectedItem = data.GetDefaultUser();
        }
        
        /// <summary>
        /// Authorize the Netflix User
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAuthorize_Click(object sender, EventArgs e)
        {
            string sUser = data.GetDefaultUser();
            
            //--------------------------------------------------------------------------------
            // Create the connection and get the access token
            //--------------------------------------------------------------------------------
            Connection conn = new Connection();
            conn.GenerateRequestToken(sUser);
            txtMessage.Text = "User is Authorized";

            //--------------------------------------------------------------------------------
            // Reload the queue users combo box
            //--------------------------------------------------------------------------------
            LoadQueueUsers();
            
            //--------------------------------------------------------------------------------
            // Cache all the images for the user queues
            //--------------------------------------------------------------------------------
            CacheQueueImages(conn);
        }

        /// <summary>
        /// Authorize Sub account
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void subAccount_Click(object sender, EventArgs e)
        {
            //--------------------------------------------------------------------------------
            // Create the connection and get the access token
            //--------------------------------------------------------------------------------
            Connection conn = new Connection();
            conn.GenerateRequestToken("");
            txtMessage.Text = "User is Authorized";

            //--------------------------------------------------------------------------------
            // Reload the queue users combo box
            //--------------------------------------------------------------------------------
            LoadQueueUsers();

            //--------------------------------------------------------------------------------
            // Cache all the images for the user queues
            //--------------------------------------------------------------------------------
            CacheQueueImages(conn);
        }


        /// <summary>
        /// Save the settings
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            Save();
            this.Close();
        }

        /// <summary>
        /// Save the settings
        /// </summary>
        private void Save()
        {
            if (txtResults.Text == "")
            {
                Log.Error("My NetFlix - MyNetFlixConfig:Save_Click: Enter # of Results.");
                MessageBox.Show("Please enter number of results.");
                return;
            }
            else if (lbInstantUsers.Items.Count < 1)
            {
                Log.Error("My NetFlix - MyNetFlixConfig:Save_Click: Enter Instant Viewers.");
                MessageBox.Show("Please enter Instant Viewers.");
                return;
            }

            //--------------------------------------------------------------------------------
            // All is good, save the settings to the database and close the window
            //--------------------------------------------------------------------------------
            data.AddSettings(txtResults.Text, chInstantOnly.Checked.ToString(), chkDetails.Checked.ToString(), cbScreen.SelectedIndex);
            txtMessage.Text = "Settings Saved";

            //--------------------------------------------------------------------------------
            // Update the default queue user
            //--------------------------------------------------------------------------------
            data.UpdateDefault(cbUsers.SelectedItem.ToString());

            Log.Info("My NetFlix - MyNetFlixConfig:Save_Click: Settings saved.");
        }

        /// <summary>
        /// Cancel the changes and close
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click_1(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// Add User to the database
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddUser_Click(object sender, EventArgs e)
        {
            //--------------------------------------------------------------------------------
            // check to make sure there is a name entered
            //--------------------------------------------------------------------------------
            if (txtUserName.Text == "")
                MessageBox.Show("Please enter a name in the textbox.");
            else
            {
                //--------------------------------------------------------------------------------
                // Add the user
                //--------------------------------------------------------------------------------
                data.AddInstantUsers(txtUserName.Text);

                //--------------------------------------------------------------------------------
                // Lets reload the list
                //--------------------------------------------------------------------------------
                LoadInstantUsers();

                Log.Info("My NetFlix - MyNetFlixConfig:AddUser_Click: User {0} was added to the database.", txtUserName.Text);

                txtUserName.Text = "";
            }
        }

        /// <summary>
        /// Cache the images for each queue
        /// </summary>
        /// <param name="_conn"></param>
        private void CacheQueueImages(Connection _conn)
        {
            //--------------------------------------------------------------------------------
            // Load the netflix user
            //--------------------------------------------------------------------------------
            User user = new User(_conn.NetFlixAccessToken, _conn);

            //--------------------------------------------------------------------------------
            // Now lets get all the items and cache the images
            //--------------------------------------------------------------------------------
            queue = new DiscQueue(user);
            ThreadStart tsDisc = delegate { CheckQueueItems(queue); };
            Thread tDisc = new Thread(tsDisc);
            tDisc.Start();

            queue = new InstantQueue(user);
            ThreadStart tsInstant = delegate { CheckQueueItems(queue); };
            Thread tInstant = new Thread(tsInstant);
            tInstant.Start();

            queue = new DiscAtHomeQueue(user);
            ThreadStart tsAtHome = delegate { CheckQueueItems(queue); };
            Thread tAtHome = new Thread(tsAtHome);
            tAtHome.Start();

            queue = new Recommendations(user);
            ThreadStart tsRecommendations = delegate { CheckQueueItems(queue); };
            Thread tRecommendations = new Thread(tsRecommendations);
            tRecommendations.Start();
        }

        /// <summary>
        /// Check Queue Items complete
        /// </summary>
        private void CheckQueueItems(Queue thisQueue)
        {
            //--------------------------------------------------------------------------------
            // Now refresh the queue to get the images
            //--------------------------------------------------------------------------------
            thisQueue.Refresh();
        }

        /// <summary>
        /// If someone clicks on the NetFlix image, send them to their website
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>       
        private void pbNetFlix_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("IEXPLORE.EXE", "http://www.netflix.com");
        }

        /// <summary>
        /// Show the PDF Help file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PDFHelp_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Show when someone clicks the about button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void About_Click(object sender, EventArgs e)
        {
            MyNetFlixAbout about = new MyNetFlixAbout();
            about.ShowDialog();
        }

        /// <summary>
        /// Save the settings
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Save();
        }

        /// <summary>
        /// Delete all the coverart and fanart
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void deleteCoverartFanartToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //------------------------------------------------------------------------------------
            // Like Microsoft, lets make sure the user really, really wants to delete the images
            //------------------------------------------------------------------------------------
            DialogResult result = MessageBox.Show("Are you sure you want to delete all the images?", "Delete Coverart & Fanart", MessageBoxButtons.YesNo);

            if (result == DialogResult.Yes)
            {
                //--------------------------------------------------------------------------------
                // Get rid of all the images My NetFlix has downloaded
                //--------------------------------------------------------------------------------
                try
                {
                    DirectoryInfo di = new DirectoryInfo(Config.GetFolder(Config.Dir.Thumbs) + "\\MyNetFlix\\");
                    di.Delete(true);

                    MessageBox.Show("Covers and BackDrops Deleted.");
                    Log.Info("My NetFlix - MyNetFlixConfig:DeleteCovers: Covers and BackDrops Deleted.");
                }
                catch (Exception ex)
                {
                    Log.Error("My NetFlix - MyNetFlixConfig:DeleteCovers(): Error - " + ex.Message);
                    MessageBox.Show("Error deleteing Covers and Backdrops.");
                }
            }
        }

        /// <summary>
        /// Close the dialog
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void closeDialog_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
